package com.avecsys.quotemanager.mbeans.supplier;

import java.io.Serializable;
import java.util.Map;

import javax.faces.context.FacesContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.avecsys.quotemanager.dao.common.EnumActor;
import com.avecsys.quotemanager.dao.common.EnumTransactionStatus;
import com.avecsys.quotemanager.exception.BaseException;
import com.avecsys.quotemanager.exception.BusinessException;
import com.avecsys.quotemanager.exception.UserSessionNotFoundException;
import com.avecsys.quotemanager.mbeans.core.BaseMBean;
import com.avecsys.quotemanager.pojos.SupplierMasterPojo;
import com.avecsys.quotemanager.pojos.SupplierUsersPojo;
import com.avecsys.quotemanager.service.common.CommonService;
import com.avecsys.quotemanager.service.supplier.SupplierMasterService;
import com.avecsys.quotemanager.service.user.UserMasterService;
import com.avecsys.quotemanager.utils.MessageBoardUtil;
import com.avecsys.quotemanager.utils.TransactionStatus;

public class SupplierUsersMBean extends BaseMBean implements Serializable {

	private final Log log = LogFactory.getLog(SupplierUsersMBean.class);

	private SupplierMasterService supplierMasterService;

	private UserMasterService userMasterService;

	private CommonService commonService;

	private SupplierUsersPojo supplierUsersPojo = new SupplierUsersPojo();

	private String selectedSupplierId;

	private String selectedSupplierCompanyName;

	private String confirmPassword;

	private String existingEmailAddress;

	public String actionCancel() {
		try {
			FacesContext faceContext = FacesContext.getCurrentInstance();
			Map<String, String> paramValues = faceContext.getExternalContext()
					.getRequestParameterMap();
			String selectedSupplierId = paramValues.get("selectedSupplierId");
			SupplierMasterPojo selectedSupplierMasterPojo = supplierMasterService
					.getSupplierMasterById(new Long(selectedSupplierId));
			SupplierUsersListMBean supplierUsersListMBean = (SupplierUsersListMBean) faceContext
					.getApplication().evaluateExpressionGet(faceContext,
							"#{supplierUsersListMBean}",
							SupplierUsersListMBean.class);
			supplierUsersListMBean
					.loadAllUsersBySupplier(selectedSupplierMasterPojo);
		} catch (BusinessException e) {
			log.error(e);
		}
		return "openListUsersForSupplier";
	}

	/**
	 * Action Method to save supplier Information
	 * 
	 * @return Navigation Page
	 */
	public String actionSaveSupplierUser() {
		try {
			log.info("Started Saving Supplier User Information into database");
			// Step1: Update user modification information
			updateUserInformation(supplierUsersPojo);
			// Step2: Get the supplierPojo associate to the user
			SupplierMasterPojo selectedSupplierMasterPojo = supplierMasterService
					.getSupplierMasterById(new Long(getSelectedSupplierId()));
			supplierUsersPojo.setSupplierMasterPojo(selectedSupplierMasterPojo);
			// Mark Email Verified status as false if the email is different
			// from the current one
			if (getExistingEmailAddress() != null
					&& !getExistingEmailAddress().equalsIgnoreCase(
							supplierUsersPojo.getUserMasterPojo().getEmail())) {
				supplierUsersPojo.getUserMasterPojo().setEmailVerfied(
						Boolean.FALSE.toString());
			}
			TransactionStatus transactionStatus = userMasterService
					.saveSupplierUser(supplierUsersPojo);
			MessageBoardUtil.publishTransactionStatusMessage(transactionStatus,
					EnumActor.SUPPLIER_USER, "messageBoardId", "",
					new Object[] { supplierUsersPojo.getUserMasterPojo()
							.getUserName() });
			// Refresh the supplier users list
			FacesContext faceContext = FacesContext.getCurrentInstance();
			SupplierUsersListMBean supplierUsersListMBean = (SupplierUsersListMBean) faceContext
					.getApplication().evaluateExpressionGet(faceContext,
							"#{supplierUsersListMBean}",
							SupplierUsersListMBean.class);
			supplierUsersListMBean
					.loadAllUsersBySupplier(selectedSupplierMasterPojo);
			// Send Verification Email
			if (transactionStatus.getStatus().intValue() == EnumTransactionStatus.SAVE_SUCESS
					.ordinal()) {
				log.info("Sending Activate Email Notification to Supplier User");
				commonService.sendEmail(supplierUsersPojo);
			} else if (transactionStatus.getStatus().intValue() == EnumTransactionStatus.UPDATE_SUCCESS
					.ordinal()) {
				// Send Notification only if user changed existing email address
				if (!getExistingEmailAddress().equalsIgnoreCase(
						supplierUsersPojo.getUserMasterPojo().getEmail())) {
					log.info("Sending Activate Email Notification to Supplier User");
					commonService.sendEmail(supplierUsersPojo);
				}
			}
			log.info("Completed saving Supplier User Information into database sucessfully");
		} catch (BaseException e) {
			log.error(e);
			MessageBoardUtil.publishException(e);
		}
		return "openListUsersForSupplier";
	}

	public CommonService getCommonService() {
		return commonService;
	}

	/**
	 * @return the confirmPassword
	 */
	public String getConfirmPassword() {
		return confirmPassword;
	}

	public String getExistingEmailAddress() {
		return existingEmailAddress;
	}

	/**
	 * @return the selectedSupplierCompanyName
	 */
	public String getSelectedSupplierCompanyName() {
		return selectedSupplierCompanyName;
	}

	/**
	 * @return the selectedSupplierId
	 */
	public String getSelectedSupplierId() {
		return selectedSupplierId;
	}

	/**
	 * @return the supplierMasterService
	 */
	public SupplierMasterService getSupplierMasterService() {
		return supplierMasterService;
	}

	public SupplierUsersPojo getSupplierUsersPojo() {
		return supplierUsersPojo;
	}

	/**
	 * @return the userMasterService
	 */
	public UserMasterService getUserMasterService() {
		return userMasterService;
	}

	public void setCommonService(CommonService commonService) {
		this.commonService = commonService;
	}

	/**
	 * @param confirmPassword
	 *            the confirmPassword to set
	 */
	public void setConfirmPassword(String confirmPassword) {
		this.confirmPassword = confirmPassword;
	}

	public void setExistingEmailAddress(String existingEmailAddress) {
		this.existingEmailAddress = existingEmailAddress;
	}

	/**
	 * @param selectedSupplierCompanyName
	 *            the selectedSupplierCompanyName to set
	 */
	public void setSelectedSupplierCompanyName(
			String selectedSupplierCompanyName) {
		this.selectedSupplierCompanyName = selectedSupplierCompanyName;
	}

	/**
	 * @param selectedSupplierId
	 *            the selectedSupplierId to set
	 */
	public void setSelectedSupplierId(String selectedSupplierId) {
		this.selectedSupplierId = selectedSupplierId;
	}

	/**
	 * @param supplierMasterService
	 *            the supplierMasterService to set
	 */
	public void setSupplierMasterService(
			SupplierMasterService supplierMasterService) {
		this.supplierMasterService = supplierMasterService;
	}

	public void setSupplierUsersPojo(SupplierUsersPojo supplierUsersPojo) {
		this.supplierUsersPojo = supplierUsersPojo;
	}

	/**
	 * @param userMasterService
	 *            the userMasterService to set
	 */
	public void setUserMasterService(UserMasterService userMasterService) {
		this.userMasterService = userMasterService;
	}

	/**
	 * Method to update the user information
	 * 
	 * @param supplierUsersPojo
	 * @throws UserSessionNotFoundException
	 */
	public void updateUserInformation(SupplierUsersPojo supplierUsersPojo)
			throws UserSessionNotFoundException {
		// Update User Information to Supplier
		super.updateUserInformation(supplierUsersPojo, null);
		// Update User Information to Company
		super.updateUserInformation(supplierUsersPojo.getUserMasterPojo(),
				supplierUsersPojo.getModifiedDttm());
	}
}
